//////////////////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2014-2015, Egret Technology Inc.
//  All rights reserved.
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are met:
//
//     * Redistributions of source code must retain the above copyright
//       notice, this list of conditions and the following disclaimer.
//     * Redistributions in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//     * Neither the name of the Egret nor the
//       names of its contributors may be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
//  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
//  OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
//  IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
//  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
//  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
//  OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
//  EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////

class Main extends egret.DisplayObjectContainer {

    /**
     * 加载进度界面
     * Process interface loading
     */
    private loadingView: LoadingUI;

    public constructor() {
        super();
        this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddToStage, this);
    }

    private QueryStringByName(name:string): string {
        return "5624e7b5c999fd6363b212ad";
        var result: RegExpMatchArray = window.location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
        if (result == null || result.length < 0) {
            return "";
        }
        return result[1];
    }

    private _albumid: string;
    private textField: egret.TextField;

    private alert(text: string): void {
        this.textField = new egret.TextField();
        this.addChild(this.textField);
        this.textField.y = 300;
        this.textField.width = 1024;
        this.textField.height = 100;
        this.textField.textAlign = "center";
        this.textField.text = text;
    }

    private onAddToStage(event: egret.Event) {
        
        // SoundManager.playSound("/resource/test/1.mp3",null);
        // setTimeout(function() {
        //     // SoundManager.stopSound();
        //     SoundManager.playSound("/resource/test/1.mp3",null);            
        // }, 500);
        // // SoundManager.playSound("http://cdn.banmaxiaozhen.com/5623673fc999fd6363b1f34e/1445256581373/audio.mp3",null)
        // return  
        this.createGameScene();
        this.loadingView = new LoadingUI();
        this.stage.addChild(this.loadingView);

        //初始化Resource资源加载库
        //initiate Resource loading library
        RES.addEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.loadConfig("resource/resource.json", "resource/");
    }

    /**
     * 配置文件加载完成,开始预加载preload资源组。
     * configuration file loading is completed, start to pre-load the preload resource group
     */
    private onConfigComplete(event: RES.ResourceEvent): void {
        RES.removeEventListener(RES.ResourceEvent.CONFIG_COMPLETE, this.onConfigComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
        RES.addEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);
        RES.loadGroup("ui");
    }

    /**
     * preload资源组加载完成
     * Preload resource group is loaded
     */
    private onResourceLoadComplete(event: RES.ResourceEvent): void {
        if (event.groupName == "ui") {

            RES.removeEventListener(RES.ResourceEvent.GROUP_COMPLETE, this.onResourceLoadComplete, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_LOAD_ERROR, this.onResourceLoadError, this);
            RES.removeEventListener(RES.ResourceEvent.GROUP_PROGRESS, this.onResourceProgress, this);

            this.startLoadPaint();
            this.addUI();
        }
    }

    private prevBtn: egret.Sprite;
    private nextBtn: egret.Sprite;


    private addUI(): void {
       
        this.nextBtn = new egret.Sprite();

        this.nextBtn.addChild(this.createBitmapByName("next"));
        this.nextBtn.touchEnabled = true;
        this.nextBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,() => { this.playNext();}, this);

        this.addChild(this.nextBtn);
        this.nextBtn.x = 1024 - 333;
        this.nextBtn.y = 768;

        //
        this.prevBtn = new egret.Sprite();

        this.prevBtn.addChild(this.createBitmapByName("prev"));
        this.prevBtn.touchEnabled = true;
        this.prevBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,() => { this.playPrev(); }, this);

        this.addChild(this.prevBtn);
        this.prevBtn.x = 0;
        this.prevBtn.y = 768;

        this.playBtn = new egret.Sprite();

        this.playBtn.addChild(this.createBitmapByName("play"));
        this.playBtn.visible = false;
        this.playBtn.touchEnabled = true;
        this.playBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,this.play, this);
        this.addChild(this.playBtn);
        this.playBtn.x = (1024 - 129) / 2;
        this.playBtn.y = (768-129)/2;

    }

    /**
     * 资源组加载出错
     *  The resource group loading failed
     */
    private onResourceLoadError(event: RES.ResourceEvent): void {
        //TODO
        console.warn("Group:" + event.groupName + " has failed to load");
        //忽略加载失败的项目
        //Ignore the loading failed projects
        this.onResourceLoadComplete(event);

    }

    /**
     * preload资源组加载进度
     * Loading process of preload resource group
     */
    private onResourceProgress(event: RES.ResourceEvent): void {
        if (event.groupName == "ui") {
            this.loadingView.setProgress(event.itemsLoaded, event.itemsTotal);
        }
    }

    private onTestLoadComplete(event: egret.Event): void {
        // var loader: egret.URLLoader = <egret.URLLoader>event.target;
        // var sound: egret.Sound = new egret.Sound();
        // sound._setAudio(loader.data);
        // sound.play();
    }

    private playground: egret.Sprite;
    private thumbList: egret.Sprite;

    /**
     * 创建游戏场景
     * Create a game scene
     */
    private createGameScene(): void {
        var stageW: number = this.stage.stageWidth;
        var stageH: number = this.stage.stageHeight;

        var background: egret.Shape = new egret.Shape();
        background.graphics.beginFill(0xffffff);
        background.graphics.drawRect(0, 0, 1024, 768);
        background.graphics.endFill();
        this.addChild(background);

        this.playground = new egret.Sprite();
        this.playground.width = 1024;
        this.playground.height = 768;
        this.playground.x = 0;
        this.playground.y = 0;
        this.addChild(this.playground);

        this.listContainer = new egret.Sprite();
        this.listContainer.y = 768;
        this.addChild(this.listContainer);

        this.listContainer.visible = false;

        var listBG: egret.Shape = new egret.Shape();
        listBG.graphics.beginFill(0x66ccff);
        listBG.graphics.drawRect(0, 0, 1024, 200);
        listBG.graphics.endFill();
        this.listContainer.addChild(listBG);

        this.thumbList = new egret.Sprite();
        //this.listContainer.addChild(this.thumbList);
        var scroller = new egret.ScrollView
        scroller.setContent(this.thumbList);
        scroller.width = 1024;
        scroller.height = 200;
        scroller.touchEnabled = true;
        this.listContainer.addChild(scroller);
       
    }

    private listContainer: egret.Sprite;

    /**
     * 开始下载画报
     */
    private startLoadPaint(): void {

        /**
        var url: string = VO.SERVICE_HOST + "/Api/album/" + this._albumid;
        $.ajax({

            url: url,
            data: {},
            type: 'GET',
            crossDomain: true,
            dataType: 'jsonp',
            success: function () { alert("Success"); },
            error: function () { alert('Failed!'); }
        });
        */

        this._albumid = decodeURIComponent(this.QueryStringByName("albumid"));
        var url: string;
        if (!this._albumid)
        {
            /*
            this.alert("出错啦");
            console.warn("画报id获取失败");
            return;
            */
            url = "resource/assets/album/test.json";
        } else
            url = VO.SERVICE_HOST + "/Api/album/" + this._albumid;

        var loader: egret.URLLoader = new egret.URLLoader();
        loader.dataFormat = egret.URLLoaderDataFormat.TEXT;

        var req: egret.URLRequest = new egret.URLRequest(url);
        req.method = egret.URLRequestMethod.GET;

        loader.addEventListener(egret.Event.COMPLETE, this.onLoadComplete, this);
        loader.addEventListener(egret.IOErrorEvent.IO_ERROR, this.onLoadError, this);
        loader.load(req);
    }

    /**
    * 解析画报详情
    */
    private onLoadComplete(event: egret.Event): void {
        console.log("onLoadComplete");
        var loader: egret.URLLoader = <egret.URLLoader>event.target;
        var str: string = decodeURIComponent(loader.data);
        var obj: any = JSON.parse(str);

        var album: any = obj.results;
        var username: string = album.author.nickname;
        var albumname: string = album.title;

        //document.title = albumname;

        var paints: any[] = album.paints;

        this.loadCount = 0;

        this.thumbList.width = (200 + 30) * (paints.length);
        this.thumbList.height = 200;

        for (var i: number = 0; i < paints.length; i++) {
            var sp = new egret.Sprite();
            sp.width = 200;
            sp.height = 180;
            sp.x = 15 + (200 + 30) * i;
            sp.y = 10;
            sp.graphics.beginFill(0xffffff);
            sp.graphics.drawRect(0, 0, 200, 180);
            sp.graphics.endFill();
            this.thumbList.addChild(sp);

            var paint: any = paints[i];
            var ploader: PaintLoader = new PaintLoader();
            ploader.initData(paint, i);
            ploader.addEventListener(egret.Event.COMPLETE, this.onPlayerLoadComp, this);
            this.loaderArr.push(ploader);
        }

        this.loadingView.setProgress(this.loadCount, this.loaderArr.length);
    }

    private onPlayerLoadComp(e: egret.Event): void {

        var ploader: PaintLoader = <PaintLoader>e.target;
        this.addThumb(ploader);

        this.loadCount++;

        this.loadingView.setProgress(this.loadCount, this.loaderArr.length);

        if (this.loadCount == this.loaderArr.length) {
            this.stage.removeChild(this.loadingView);
            this.playBtn.visible = true;
            this.playBtn.touchEnabled = true;
            this.playIndex = 0;
            this.touchEnabled = true;

           // this.addPlayer(this.loaderArr[this.playIndex], false);
           // this.play();
        }
    }

    private addThumb(ploader: PaintLoader): void {
        var index = this.loaderArr.indexOf(ploader);
        var sp: egret.Sprite = <egret.Sprite>this.thumbList.getChildAt(index);
        var thumb: egret.Bitmap = new egret.Bitmap(ploader.getRes(ploader.paint.cover));
        thumb.width = 200;
        thumb.height = 150;
        thumb.y = 5;
        sp.addChild(thumb);
        thumb.touchEnabled = true;
        thumb.addEventListener(egret.TouchEvent.TOUCH_TAP, this.onThumbClick, this)

        var title = new egret.TextField();
        title.textColor = 0;
        title.size = 18;
        title.width = 50;
        title.height = 20;
        title.fontFamily = "黑体";
        title.textAlign = "center";
        sp.addChild(title);
        title.x = 5;
        title.y = 150 + 5 + 5;
        title.text = (index+1) + ".";

        var typeText = new egret.TextField();
        typeText.textColor = 0;
        typeText.size = 18;
        typeText.width = 50;
        typeText.height = 20;
        typeText.fontFamily = "黑体";
        title.textAlign = "center";
        sp.addChild(typeText);
        typeText.x = 200 - 10 - 50;
        typeText.y = 150 + 5 + 5;
        typeText.text = ploader.type;
    }

    private onThumbClick(e: egret.TouchEvent): void {
        var thumb: egret.Bitmap = <egret.Bitmap>e.target;
        var index = this.thumbList.getChildIndex(thumb.parent);
        this.playIndex = index;
        this.play();
    }

    private loaderArr: Array<PaintLoader> = new Array<PaintLoader>();

    private play(): void {
        if (this.playground.numChildren) {
            var crtPlayer: PlayerBase = <PlayerBase>this.playground.getChildAt(0);
            crtPlayer.removeEventListener(egret.Event.COMPLETE, this.onPlayComp, this);
            crtPlayer.dispose();
        }
        if (this.playIndex > this.loaderArr.length - 1) {
            this.playIndex = this.loaderArr.length - 1;
            return;
        } else if (this.playIndex < 0) {
            //this.alert("结束啦");
            //this.playBtn.visible = true;
            this.playIndex = 0;
            return;
        }
        this.playBtn.visible = false;

        this.addPlayer(this.loaderArr[this.playIndex],true);
    }

    private addPlayer(loader: PaintLoader,autoplay:boolean): void {

        this.playground.removeChildren();
        var player: PlayerBase;
        switch (loader.type) {
            case "图片": {
                player = new PaintPlayer();

                break;
            };
            case "故事": {
                player = new PaintPlayer();
                break;
            };
            case "动画": {
                player = new AnimePlayer();
                break;
            };
            case "问答": {
                player = new QuizPlayer();
                break;
            };
            case "视频": {
                player = new VideoPlayer();
                break;
            };
        }

        if (player != null) {
            // player.addEventListener(egret.Event.COMPLETE, this.onPlayComp, this);
            player.addEventListener(egret.Event.COMPLETE, this.onPlayCBFactory(autoplay) , this);
            player.initData(loader);
            this.playground.addChild(player);
            // if (autoplay)
            //     player.play();
        }
    }

    private onPlayCBFactory(isAutoPlay:boolean):Function {
        return function onPlayComp (event: egret.Event): void {
            var player: PlayerBase = <PlayerBase>this.playground.getChildAt(0);
            player.stop();
            this.playBtn.visible = true;
    
            if(isAutoPlay){
                this.playNext();
            }
        }
        
    }
    private onPlayComp(event: egret.Event): void {
        var player: PlayerBase = <PlayerBase>this.playground.getChildAt(0);
        player.stop();
        this.playBtn.visible = true;

        this.playNext();
    }

    private playBtn:egret.Sprite;

    private playNext(): void {
        this.playIndex++;
        this.play();
    }

    private playPrev(): void {
        this.playIndex--;
        this.play();
    }

    private loadCount: number = 0;

    private playIndex: number = 0;

    private onLoadError(): void {
        console.log("onLoadError");
    }

    /**
     * 根据name关键字创建一个Bitmap对象。name属性请参考resources/resource.json配置文件的内容。
     * Create a Bitmap object according to name keyword.As for the property of name please refer to the configuration file of resources/resource.json.
     */
    private createBitmapByName(name: string): egret.Bitmap {
        var result: egret.Bitmap = new egret.Bitmap();
        var texture: egret.Texture = RES.getRes(name);
        result.texture = texture;
        return result;
    }
}


